<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>解决：ios手机底部输入框被软键盘遮挡的bug</title>
  <meta name="author" content="艺灵,www.yilingsj.com" />
  <meta name="tag" content="移动端,ios,输入框,fixed悬浮,软键盘,input,斗鱼,映客,直播,bug,scrollIntoViewIfNeeded,scrollIntoView" />
  <meta name="description" content="做过移动端聊天功能的看官都知道在ios苹果手机上有bug，就是当底部输入框获取焦点时容易被软键盘遮挡住。即使是斗鱼、映客等直播平台也有此bug！而网上偏方也是多的去了，但并没有一个很好的解决方案。而且有些文章是信口开河，用pc端相当然的js方法用到移动端上，真是害人不浅！而本文是艺灵经过大量测试后才发布的，文章会提供一个完整的功能演示demo，方便看官体验。">
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta content="yes" name="apple-mobile-web-app-capable">
  <meta content="yes" name="apple-touch-fullscreen">
  <meta content="telephone=no,email=no" name="format-detection">
  <meta name="viewport" content="initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no">
  <style>
    *{padding:0;margin:0}li{list-style:none}html,body,.container{height:100%;width:100%}.container{display:flex;display:-webkit-flex;flex-direction:column;width:100%;height:100%;background:#C2BE9E}.content{-webkit-overflow-scrolling:touch;flex:1;-webkit-flex:1;width:100%;position:relative;overflow-y:scroll;background-color:#ffd865;opacity:.5}.flex{display:flex;flex-wrap:wrap}.flex-1{flex:1}.space-between{justify-content:space-between}.align-items{align-items:center;display:flex}.demo-text{position:absolute;top:0px;width:100%;box-sizing:border-box;background:#000;font-size:10px;opacity:.5;line-height:14px;padding:5px;height:200px;overflow-y:auto;color:#fff;word-wrap:break-word}.ul-imgChat{}.li-imgChat>.box{padding:10px 0}.li-imgChat+.li-imgChat>.box,.li-imgChat.base_right+.li-imgChat.base_right>.box{padding-top:0}.li-imgChat.base_right+.li-imgChat>.box,.li-imgChat.base_right>.box{padding-top:10px}.li-imgChat>.box>.time{color:rgba(204,204,204,1);text-align:center;margin-top:10px}.li-imgChat>.box>.time>span:not(:last-child){margin-right:10px}.li-imgChat>.box>.hd{margin-right:10px}.li-imgChat>.box>.bd{margin-right:50px}.li-imgChat>.box>.bd>.box,li.li-imgChat.hetong>.box>.bd>.box{background:rgba(250,250,250,1);padding:5px 10px;border-radius:17px;display:inline-block}li.li-imgChat.hetong>.box>.bd>.box{padding:10px}.li-imgChat .tit{color:rgba(102,102,102,1);line-height:24px;min-height:24px;height:auto}.li-imgChat.base_right>.box,.li-imgTit.base_right>.box{flex-direction:row-reverse;text-align:right}.li-imgChat.base_right>.box>.hd,.li-imgTit.base_right>.box>.hd{margin-right:0;margin-left:20px}.li-imgChat.base_right>.box>.bd>.box{background:rgba(0,120,255,1)}.li-imgChat.base_right>.box>.bd{margin-right:0;margin-left:50px}.li-imgChat.base_right .tit{color:rgba(255,255,255,1)}.li-input-fasong{width:100%;position:relative;z-index:99999}.li-input-fasong>.box{padding:2px 16px}.li-input-fasong>.box>.bd{padding-left:16px}.li-input-fasong .textarea::-webkit-input-placeholder{color:rgba(204,204,204,1)}.li-input-fasong .textarea{height:22px;font-size:16px;caret-color:#0078FF;width:100%;font-family:PingFangSC-Light;color:rgba(51,51,51,1);vertical-align:top;line-height:22px;;padding:12px 0 10px;resize:none}.icon-fasong{font-size:24px;display:inline-block;font-style:normal;width:24px;height:24px;line-height:22px;background-color:#0078ff;color:#fff;border-radius:50%;position:relative;text-align:center;font-family:\5FAE\8F6F\96C5\9ED1}.fluid{width:100%}.none{display:none}.tabs-chat{padding:40px 0;display:none;text-align:center;font-size:18px}.footer{background-color:#ccc;opacity:.8;position:relative;z-index:999999}.pop-chat-bg{position:fixed;left:0;top:0;width:100%;height:100%;background:transparent;cursor:pointer;z-index:9998}.li-input-fasong>.box>.bd{padding-left:16px}.bdshare-slide-button-box,iframe{display:none !important}
  </style>
</head>
  <body>
    <div class="container">
      <div class="content">
        <div class="box-chat p010">
          <div class="box">
            <ul class="ul-imgChat bgc-fff clearfix">
              <li class="li-imgChat pr">
                <div class="box">
                  <div class="time">
                    <span>2017-12-19</span>
                    <span>12:47:45</span>
                  </div>
                </div>
              </li>
              <li class="li-imgChat pr base_right">
                <div class="box flex space-between">
                  <div class="hd">
                    <div class="img-w-32"></div>
                  </div>
                  <div class="bd flex-1">
                    <div class="box">
                      <div class="tit">1你好，我是</div>
                    </div>
                  </div>
                </div>
              </li>
            </ul>
            <h2 style="position:absolute;bottom:100px">
              <a href="http://www.yilingsj.com/xwzj/2018-07-05/ios-input-bug.html" title="移动端填坑之路之ios手机底部悬浮输入框的bug">返回原文</a>
            </h2>
          </div>
        </div>
      </div>
      <div class="box footer">
        <ul class="ul-input-fasong flex clearfix">
          <li class="li-input-fasong pr">
            <form class="box flex space-between">
              <div class="hd flex-1">
                <div class="box">
                  <textarea name="textarea" class="textarea f-input text-chat text-chat1" placeholder="请输入回复内容" data-config="{&quot;id&quot;:&quot;text&quot;,&quot;par&quot;:&quot;.footer&quot;,&quot;sib&quot;:&quot;.tabs-chat,.pop-chat-bg&quot;,&quot;showclass&quot;:&quot;on&quot;,&quot;bodyclass&quot;:&quot;auto-body&quot;,&quot;type&quot;:&quot;chat&quot;,&quot;popbg&quot;:&quot;.pop-chat-bg&quot;,&quot;fixinput&quot;:&quot;1&quot;}"></textarea>
                  <input type="reset" name="reset" id="reset" class="none" />
                </div>
              </div>
              <div class="bd align-items">
                <div class="box">
                  <i class="icon icon-fasong cursor f-click" data-config="{&quot;id&quot;:&quot;popChat&quot;,&quot;par&quot;:&quot;.ul-input-fasong&quot;,&quot;sib&quot;:&quot;.tabs-chat&quot;,&quot;bodyclass&quot;:&quot;auto-body&quot;,&quot;popbg&quot;:&quot;.pop-chat-bg&quot;,&quot;showid&quot;:&quot;.tabs-chat&quot;}">+</i>
                </div>
            </form>
            </div>
          </li>
        </ul>
        <div class="tabs tabs-chat">
          <div class="txt">此处内容省略......</div>
        </div>
      </div>
    </div>
    <script src="https://cdn.bootcss.com/jquery/1.8.3/jquery.min.js"></script>
    <script>
      ;(function(){var bp=document.createElement('script');var curProtocol=window.location.protocol.split(':')[0];if(curProtocol==='https'){bp.src='https://zz.bdstatic.com/linksubmit/push.js'}else{bp.src='http://push.zhanzhang.baidu.com/push.js'}var s=document.getElementsByTagName("body")[0];s.appendChild(bp)})();var _hmt=_hmt||[];(function(){var hm=document.createElement("script");hm.src="//hm.baidu.com/hm.js?6b8357f33986ae0068aecde163805563";var s=document.getElementsByTagName("body")[0];s.appendChild(hm)})();window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"slide":{"type":"slide","bdImg":"4","bdPos":"right","bdTop":"200"}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];(function(){var config={itv:1800000,url1:'//ia.51.la/go1?id=17109514',ekc:''};var cre51=document.createElement('a');cre51.href='//www.51.la/?comId=17109514';cre51.setAttribute('title','51.La \u7f51\u7ad9\u6d41\u91cf\u7edf\u8ba1\u7cfb\u7edf');cre51.setAttribute('target','_blank');cre51.style.display='none';cre51.innerText='51La';document.body.appendChild(cre51);!function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function r(){var e=void 0,t=/id=(\d+)/.exec(config.url1)[1]||"";try{e=u.get("__tins__"+t)}catch(t){e=!1}var n=e&&i.isN(e.sid)&&i.isN(e.expires)&&g-e.sid<18e5?0:1,r=n?1:e.vd+1,o=n?g:e.sid,c=g+18e5;return u.set("__tins__"+t,s.stringify({sid:o,vd:r,expires:c}),null,"/"),[n,n?o:u.get("__tins__"+t).sid,r]}function o(){var e=s.parse(s.stringify(i.extend({},y,v))),t=i.obj2url(e),n=config.url1+"&rt="+g+"&"+t,r=new Image(1,1);r.src=n}var i=n(4),c=n(5),u=n(7).store,s=n(6),a=window,f=a.location,l=a.screen,p=a.navigator,g=i.now(),d=!0,m=r(),v={ekc:config.ekc,sid:m[1],tt:c.getMeta.tt,kw:c.getMeta.kw,cu:f.href,pu:c.getRef()},y={rl:l.width+"*"+l.height,lang:p.language||p.browserLanguage,ct:function(){var e=p.connection||p.mozConnection||p.webkitConnection||p.oConnection,t=i.hasIt(p.userAgent,"mobile")&&e?e.type:"unknow";return t}(),pf:function(){var e=d?1:0;return d=0,e}(),ins:m[0],vd:m[2],ce:p.cookieEnabled?1:0,cd:l.colorDepth||l.pixelDepth,ds:c.getMeta.ds};o.version="2.2.1.2",n(10)(y),o()},,,,function(e,t){"use strict";function n(e,t){return void 0!==e&&e.indexOf(t)!==-1}function r(e){return function(t){return Object.prototype.toString.call(t)==="[object "+e+"]"}}function o(){for(var e=0,t={};e<arguments.length;e++){var n=arguments[e];for(var r in n)t[r]=n[r]}return t}function i(e){return e.replace(/&/g,"~_~")}function c(e){var t="";for(var n in e)""!==t&&(t+="&"),t+=n+"="+a(a(i(String(e[n]))));return t}function u(e){return e.replace(/^\s+|\s+$/g,"")}function s(){return+new Date}var a=encodeURIComponent,f=r("Object"),l=r("Number"),p=r("String"),g=r("Array"),d=r("Function"),m=r("RegExp");e.exports={isO:f,isN:l,isF:d,isR:m,isS:p,isA:g,hasIt:n,extend:o,obj2url:c,trim:u,now:s}},function(e,t,n){"use strict";function r(e){return u.getElementsByTagName(e.toLowerCase())}function o(){var e="";try{e=c.top.document.referrer}catch(t){if(c.parent)try{e=c.parent.document.referrer}catch(t){e=""}}return""===e&&(e=u.referrer),e}var i=n(4),c=window,u=c.document,s=function(){var e=r("meta"),t=r("title"),n={kw:"",ds:""},o=void 0;n.tt=i.trim(t.length?t[0].innerHTML:"");for(var c=0;c<e.length;c++)e[c].name&&(o=e[c].name.toLowerCase(),i.hasIt("keywords",o)&&(n.kw=e[c].content.slice(0,100)),i.hasIt("description",o)&&(n.ds=e[c].content.slice(0,30)));return n}();e.exports={getMeta:s,getRef:o}},function(module,exports){"use strict";var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};module.exports={parse:function parse(sJSON){return eval("("+sJSON+")")},stringify:function(){function e(o){if(null==o)return"null";if("number"==typeof o)return isFinite(o)?o.toString():"null";if("boolean"==typeof o)return o.toString();if("object"===("undefined"==typeof o?"undefined":_typeof(o))){if("function"==typeof o.toJSON)return e(o.toJSON());if(r(o)){for(var u="[",s=0;s<o.length;s++)u+=(s?", ":"")+e(o[s]);return u+"]"}if("[object Object]"===t.call(o)){var a=[];for(var f in o)n.call(o,f)&&a.push(e(f)+": "+e(o[f]));return"{"+a.join(", ")+"}"}}return'"'+o.toString().replace(c,i)+'"'}var t=Object.prototype.toString,n=Object.prototype.hasOwnProperty,r=Array.isArray||function(e){return"[object Array]"===t.call(e)},o={'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t"},i=function(e){return o[e]||"\\u"+(e.charCodeAt(0)+65536).toString(16).substr(1)},c=/[\\"\u0000-\u001F\u2028\u2029]/g;return e}()}},function(e,t,n){"use strict";var r=n(5),o=n(6),i={get:function(e){return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(e).replace(/[-.+*]/g,"\\$&")+"\\s*\\=s*([^;]*).*$)|^.*$"),"$1"))||null},set:function(e,t,n,r,o,i){if(!e||/^(?:expires|max-age|path|domain|secure)$/i.test(e))return!1;var c="";if(n)switch(n.constructor){case Number:c=n===1/0?"; expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+n;break;case String:c="; expires="+n;break;case Date:c="; expires="+n.toUTCString()}return document.cookie=encodeURIComponent(e)+"="+encodeURIComponent(t)+c+(o?"; domain="+o:"")+(r?"; path="+r:"")+(i?"; secure":""),!0}},c={get:function(e){return o.parse((r.isMobi?window.localStorage.getItem(e):i.get(e))||"{}")},set:function(e,t,n,o){return r.isMobi?window.localStorage.setItem(e,t):i.set(e,t,n,o)}};e.exports={cookie:i,store:c}},,,function(e,t,n){"use strict";var r=n(4),o=n(7);e.exports=function(e){var t=o.store.get("__51laig__");t=r.isN(t)?parseInt(t)+1:1,o.cookie.set("__51cke__",config.ekc,null,"/"),e.ing=t,o.store.set("__51laig__",t,null,"/")}}])}());;
    </script>
    <script type="text/javascript">
      if (typeof Y === 'undefined') {
        var Y = {};
      }
      $(window).load(function () {
        Y.navigator = navigator.userAgent.toLowerCase();
        $(document).on('keypress', ".text-chat", function (e) {
          // console.log('最外面的keypress')
          //换行键发送，别问我为什么不提供【发送】按钮，需求！！！
          if (e.keyCode == 13) {
            Y.chatstr =
              '<li class="li-imgChat pr base_right"><div class="box flex space-between"><div class="hd"><div class="img-w-32"></div></div><div class="bd flex-1"><div class="box"><div class="tit">' +
              $(".text-chat").val() + '</div></div></div></div></li>';
            $('.ul-imgChat').append(Y.chatstr);
            $(".text-chat").val('');
            if (Y.setInputNbsp) {
              clearTimeout(Y.setInputNbsp);
            }
            Y.setInputNbsp = setTimeout(function () {
              $(".text-chat").val($(".text-chat").val().trim());
            }, 50);


            if (Y.autoScroll) {
              clearTimeout(Y.autoScroll);
            }
            Y.autoScroll = setTimeout(function () {
              //时时滚动最新聊天内容到当前窗口中
              if (document.body.scrollHeight < $('.content')[0].scrollHeight + $('.footer').height()) {
                $('.content').animate({
                  'scrollTop': ($('.content')[0].scrollHeight + $('.footer').height()) + 'px'
                }, 150);
              }
            }, 300);
          }
        })


        //页面打印数据
        if ($('.text-chat').length) {
          $('body').append('<div class="demo-text">scrollH：' + document.body.scrollHeight + '；w.oH:' + window.outerHeight +
            '；w.iH:' + window.innerHeight + ';w.h:' + $(window).height() + ';b.cH:' + document.body.clientHeight +
            ';b.oH:' + document.body.offsetHeight + ';b.h:' + $("body").height() + ';b.scroll:' + document.body.scrollTop +
            ';w.sY:' + window.scrollY + ';w.top:' + $(window).scrollTop() + ';top:' + $('.text-chat').offset().top +
            ';chat.hei:' + $('.box-chat')[0].scrollHeight + ';con.h:' + $('.content')[0].scrollHeight + '</div>');
        }


        $(document).on('focus', '.text-chat', function (e) {
          console.log('被聚焦')
          var nthis = this,
            e = e || window.event,
            con = $(this).attr('data-config') ? $(this).attr('data-config') : '{}';
          con = JSON.parse(con);
          if (con.fixinput) {
            Y.inputdatabef = {};
            /*if(/[A-Za-z]/.test($(nthis).val())){
            	$(nthis).blur();
            	$(nthis).focus();
            }*/
            $('.tabs-chat').css('display', 'none');
            if (con.popbg) {
              if (!$(con.popbg).length) {
                Y.popbg({
                  cla: con.popbg
                });
              }
              $(con.popbg).fadeIn(300);
            }
            if (Y.inpfocus) {
              clearTimeout(Y.inpfocus);
            }
            Y.inpfocus = setTimeout(function () {
              $('.demo-text').append('<hr>获焦：scrollH：' + document.body.scrollHeight + '；w.oH:' + window.outerHeight +
                '；w.iH:' + window.innerHeight + ';w.h:' + $(window).height() + ';b.cH:' + document.body.clientHeight +
                ';b.oH:' + document.body.offsetHeight + ';b.h:' + $("body").height() + ';b.scroll:' +
                document.body.scrollTop + ';w.sY:' + window.scrollY + ';w.top:' + $(window).scrollTop() +
                ';top:' + $('.text-chat').offset().top + ';chat.hei:' + $('.box-chat')[0].scrollHeight +
                ';con.h:' + $('.content')[0].scrollHeight);
            }, 200);


            if (Y.inpfocusScroll) {
              clearTimeout(Y.inpfocusScroll);
            }
            Y.inpfocusScroll = setTimeout(function () {
              document.body.scrollTop = document.body.scrollHeight;
              $('.demo-text').append('<hr>滚动后scrollH：' + document.body.scrollHeight + '；w.oH:' + window.outerHeight +
                '；w.iH:' + window.innerHeight + ';w.h:' + $(window).height() + ';b.cH:' + document.body.clientHeight +
                ';b.oH:' + document.body.offsetHeight + ';b.h:' + $("body").height() + ';b.scroll:' +
                document.body.scrollTop + ';w.sY:' + window.scrollY + ';w.top:' + $(window).scrollTop() +
                ';top:' + $('.text-chat').offset().top + ';chat.hei:' + $('.box-chat')[0].scrollHeight +
                ';con.h:' + $('.content')[0].scrollHeight);


              if (Y.safariScroll) {
                clearTimeout(Y.safariScroll);
              }
              Y.safariScroll = setTimeout(function () {  
                // 当前屏幕高度362
                // alert(document.body.scrollHeight)

                // 聊天高度312 
                // alert($('.content')[0].scrollHeight)

                // 输入框高度50
                // alert($('.footer').height())

                var test = document.querySelectorAll('.footer')[0];
                test.style.backgroundColor = '#DD001A';
                if (Y.navigator.indexOf('safari\/') != -1) {
                  // 屏幕高度小于 内容区高度 + 输入框的高度
                  if (document.body.scrollHeight < $('.content')[0].scrollHeight + $('.footer').height()) {
                    
                    $('.content').animate({
                      'scrollTop': ($('.content')[0].scrollHeight + $('.footer').height()) + 'px'
                    }, 150);

                  }
                  document.body.scrollTop = window.innerHeight + 7;
                }
                test.style.backgroundColor = '#93D1FF';
              }, 100)

            }, 300);
          }
        });


        $(document).on('blur', '.text-chat', function (e) {
          $("#reset").click();
          $('.tabs-chat,.pop-chat-bg').css('display', 'none');
          if (Y.inpblur) {
            clearTimeout(Y.inpblur);
          }
          Y.inpblur = setTimeout(function () {
            $('.demo-text').append('<hr>失焦scrollH：' + document.body.scrollHeight + '；w.oH:' + window.outerHeight +
              '；w.iH:' + window.innerHeight + ';w.h:' + $(window).height() + ';b.cH:' + document.body.clientHeight +
              ';b.oH:' + document.body.offsetHeight + ';b.h:' + $("body").height() + ';b.scroll:' +
              document.body.scrollTop + ';w.sY:' + window.scrollY + ';w.top:' + $(window).scrollTop() +
              ';top:' + $('.text-chat').offset().top + ';chat.hei:' + $('.box-chat')[0].scrollHeight +
              ';con.h:' + $('.content')[0].scrollHeight);
          }, 600);
        });
        $('body').on('touchstart', '.f-click', function (e) {
          var nthis = this,
            e = e || window.event,
            con = $(this).attr('data-config') ? $(this).attr('data-config') : '{}';
          con = JSON.parse(con);
          switch (con.id) {
            case "popChat":
              $('.text-chat').blur();
              $(con.sib).slideDown(300);
              if (!$(con.popbg).length) {
                Y.popbg({
                  cla: con.popbg
                });
              }
              $(con.popbg).fadeIn(300);
              if (Y.touchstr) {
                clearTimeout(Y.touchstr);
              }
              Y.touchstr = setTimeout(function () {
                $('.demo-text').append('<hr>按钮：scrollH：' + document.body.scrollHeight + '；w.oH:' + window.outerHeight +
                  '；w.iH:' + window.innerHeight + ';w.h:' + $(window).height() + ';b.cH:' + document.body
                  .clientHeight + ';b.oH:' + document.body.offsetHeight + ';b.h:' + $("body").height() +
                  ';b.scroll:' + document.body.scrollTop + ';w.sY:' + window.scrollY + ';w.top:' + $(
                    window).scrollTop() + ';top:' + $('.text-chat').offset().top + ';chat.hei:' + $(
                    '.box-chat')[0].scrollHeight + ';con.h:' + $('.content')[0].scrollHeight);
              }, 1000);
              break;
              //弹层背景点击关闭
            case "popbg-close":
              $(nthis).css('display', 'none');
              if ($('.text-chat').length) {
                $('.text-chat').blur();
              }
              break;
            default:
              break;
          }
        });
      });
      Y.substr = function (v) {
        var a = v.substring(0, 1);
        if (a == '.' || a == '#') {
          v = v.substring(1);
        }
        return v;
      };
      Y.popbg = function (a) {
        if (!$(a.cla).length) {
          a.typ ? a.typ : a.typ = 1;
          a.top ? a.top : a.top = 0;
          a.popbg ? a.popbg : a.popbg = 1;
          $('body').append('<div class="pop-bg f-click fixed ' + Y.substr(a.cla) +
            '" data-config=\'{"id":"popbg-close","type":"' + a.typ + '","popbg":"' + a.popbg + '"}\' style="top:' +
            a.top + 'px"></div>');
        }
      };

    </script>
  </body>

</html>
